package org.idea.qiyu.framework.rpc.dubbo.monitor.report;

import com.alibaba.fastjson.JSON;
import org.idea.qiyu.cache.redis.service.IRedisService;
import org.idea.qiyu.framework.rpc.dubbo.monitor.bo.ThreadPoolInfo;
import org.idea.qiyu.framework.rpc.dubbo.monitor.service.DubboMonitorHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * dubbo线程池的上报器
 *
 * @Author linhao
 * @Date created in 5:17 下午 2022/6/29
 */
@Configuration
public class DubboMonitorReporter implements Runnable{

    @Resource
    private IRedisService iRedisService;
    @Resource
    private DubboMonitorHandler dubboMonitorHandler;

    private static String queueKey = "dubbo:threadpool:info";


    private boolean recordInfo(ThreadPoolInfo threadPoolInfo){
        iRedisService.lpush(queueKey, JSON.toJSONString(threadPoolInfo));
        return true;
    }

    @Override
    public void run() {
        while (true) {
            try {
                ThreadPoolExecutor threadPoolExecutor = dubboMonitorHandler.getDubboThreadPoolInfo();
                ThreadPoolInfo threadPoolInfo = new ThreadPoolInfo();
                threadPoolInfo.setCorePoolSize(threadPoolExecutor.getCorePoolSize());
                threadPoolInfo.setQueueLength(threadPoolExecutor.getQueue().size());
                threadPoolInfo.setExecuteTime(System.currentTimeMillis());
                this.recordInfo(threadPoolInfo);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
